package com.base.component.ai.workflow.handle;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.base.component.ai.agent.bo.ContextBO;
import com.base.component.ai.agent.bo.ContextParamBO;
import com.base.component.ai.platform.prompt.PromptTextRawService;
import com.base.component.ai.workflow.core.NodeHandle;
import com.base.component.ai.workflow.flow.Flow;
import com.base.component.ai.workflow.logs.NodeLog;
import com.base.component.ai.workflow.logs.NodeLogLLM;
import com.base.component.ai.workflow.node.Node;
import com.base.component.ai.workflow.node.NodeLLM;
import com.base.core.head.enums.ValueTypeEnum;
import com.gitee.magic.core.json.JsonArray;
import com.gitee.magic.core.json.JsonObject;

@Component
public class NodeHandleLLM<MSG,AP extends ContextParamBO,PP> implements NodeHandle<MSG,AP,PP>{

	@Autowired
	private PromptTextRawService promptTextRawService;
	
	@Override
	public <T extends Node> boolean support(Class<T> cls) {
		return cls.equals( NodeLLM.class);
	}

	@Override
	public <T extends Node>List<Flow> execute(ContextBO<MSG,AP,PP> context,Map<String,Object> params,Flow flow,T node,Consumer<NodeLog> c) {
		ContextParamBO contextParam=context.getContextParam();
		NodeLLM d=(NodeLLM)node;
		NodeLogLLM<MSG,AP,PP> nodeLog=new NodeLogLLM<>();
		nodeLog.setContext(context);
		nodeLog.setParams(params);
		String content=promptTextRawService.execute(d.getCode(), contextParam.getLanguage(), params);
		nodeLog.setContent(content);
		c.accept(nodeLog);
		
		if(d.getValueType()==ValueTypeEnum.String) {
			params.put(d.getVariableName(),content);
		}else if(d.getValueType()==ValueTypeEnum.JSONObject) {
			params.put(d.getVariableName(), new JsonObject(content));
		}else if(d.getValueType()==ValueTypeEnum.JSONArray) {
			params.put(d.getVariableName(), new JsonArray(content));
		}
		return flow.getNexts();
	}
	
}
